package com.huli.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.huli.domain.SysUser;
import com.huli.mapper.SysUserMapper;
import com.huli.service.SysUserService;
import com.huli.util.CaptchaUtil;
import com.huli.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
* @author 张庆阳
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2025-03-17 10:53:46
*/
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public boolean login(String phone, int captcha) throws Exception {
        //检查手机号是否存在
        String phone1 = sysUserMapper.getPhone(phone);
        if (!phone1.equals(phone)){
            throw  new Exception("手机号不存在");
        }
        //构造redis中的验证码键
        String redisKey="verifyCode:"+phone;
        //从redis中获取验证码
        Object redisCode = redisClient.get(redisKey);
        System.out.println(redisCode);
        if (redisCode==null){
            throw new Exception("验证码已过期或不存在");
        }
        //登录
        boolean login = sysUserMapper.login(phone, captcha);
        if (!login){
            throw new Exception("手机号或验证码错误");
        }
        //验证码比对
        if (redisCode.equals(captcha)){
            //验证成功删除验证码
            redisClient.del(redisKey);
            return true;
        }else {
            //验证失败，不删除验证码
            return false;
        }
    }

    @Override
    public void creteCaptcha(String phone) throws Exception {
        // 构造Redis中的验证码键
        String redisKey="verifyCode:"+phone;
        // 检查Redis中是否已经存在验证码
        String existingCode = (String) redisClient.get(redisKey);
        if (existingCode != null) {
            // 验证码已存在且未过期，拒绝再次发送
            throw new Exception("验证码已发送，请稍后再试！");
        }
        //生成6位随机数
        String captcha;
        do {
            captcha = CaptchaUtil.generateCaptcha(6);
        } while (captcha.charAt(0) == '0');
        //添加到reids
        redisClient.set(redisKey,captcha);
        //修改mysql里的数据
        sysUserMapper.insertCaptcha(phone,Integer.parseInt(captcha));
    }

    @Override
    public List<SysUser> findAll() {
        return sysUserMapper.findAll();
    }

    @Override
    public SysUser findById(String id) {
        return sysUserMapper.findById(id);
    }


}




